package com.example.pei.ithinklearnt.present;

import com.example.pei.ithinklearnt.AppApplication;
import com.example.pei.ithinklearnt.bean.Skill;
import com.example.pei.ithinklearnt.bean.UserInfo;
import com.example.pei.ithinklearnt.model.SkillModel;
import com.example.pei.ithinklearnt.model.SkillModelImp;
import com.example.pei.ithinklearnt.utils.ToastUtil;
import com.example.pei.ithinklearnt.view.interfaces.DetailedInformationInterface;

import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.QueryListener;

import static com.example.pei.ithinklearnt.utils.MyUtils.isNetworkAvailable;

public class DetailedInformationPresentImp implements DetailedInformationPresent {

    private DetailedInformationInterface detailedInformationInterface;
    private SkillModel skillModel;




    public DetailedInformationPresentImp(DetailedInformationInterface detailedInformationInterface1){
        this.detailedInformationInterface=detailedInformationInterface1;
        this.skillModel=new SkillModelImp();
    }

    @Override
    public void requestUserSkills(UserInfo user, final boolean isCache) {
        final String username=user.getUsername();
        if(isCache) {  //如果设置了缓存的话，则可以从本地读取
            String[] weak = skillModel.readWeakSkills(username);
            String[] strong = skillModel.readStrongSkills(username);
            detailedInformationInterface.bindingSkills(weak, strong);
        }

        //如果网络可用，则从网上更新
        if(isNetworkAvailable(AppApplication.getContext())){
            skillModel.achieveUserSkills(user, new SkillModelImp.achieveUserSkillsListener() {
                @Override
                public void succeed(String[] weakSkills, String[] strongSkills) {
                    detailedInformationInterface.bindingSkills(weakSkills,strongSkills);     //绑定
                    //如果需要在本地缓存
                    if(isCache){
                        //更新本地的数据
                        if(weakSkills!=null)
                            skillModel.writeUserWeakSkillsToLocal(username,weakSkills);
                        if(strongSkills!=null)
                            skillModel.writeUserStrongSkillsToLocal(username,strongSkills);
                    }

                }

                @Override
                public void failed() {
                }
            });
        }



    }
}
